<?php


namespace app\api\model;


use app\common\library\IDMan;
use app\common\library\PlatformModel;
use app\common\library\StatModel;
use app\common\model\BaseModel;
use common;
use think\facade\Log;

class UserChargeRideOrderModel extends BaseModel
{
    protected $name = 'user_charge_ride_order';
    protected $pk = 'id';

    //微信用户支付
    function submit_wxmp($city_id, $userinfo, $amount,$ride_order_id,$coupon_id,$coupon_amount = 0,$use_score = 0)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $profit_share = PlatformModel::get_city_profit_share($city_id,$userinfo['id']);
        $is_profit = $profit_share ? 1:0;

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxmp_unifield_order($city_id, ORDER_TYPE_USER_RIDE_CHARGE, $order_id, $amount, '骑行支付',$pay_city,$is_profit);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }


        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        $prepay_info = [
            'appId' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepay_id'],
            'nonceStr' => uniqid(),
            'timeStamp' => time(),
            'signType' => 'MD5',
            // 'partnerid' => $ret['mch_id'],
        ];

        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGERIDE_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'ride_order_id' => $ride_order_id,
            'coupon_id' => $coupon_id,
            'coupon_amount' =>$coupon_amount,
            'pay_city' => $pay_city,
            'use_score' => $use_score,
            'is_profit' => $is_profit,
        ];

        self::create($order_info);
        return $prepay_info;
    }

    //支付宝用户支付
    function submit_alipay($city_id, $userinfo, $amount,$ride_order_id,$coupon_id,$coupon_amount = 0,$use_score = 0)
    {
        $alipay_user_id = $userinfo['alipay_user_id'];

        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $profit_share = PlatformModel::get_city_profit_share($city_id,$userinfo['id']);
        $is_profit = $profit_share ? 1:0;

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade($city_id, ORDER_TYPE_USER_RIDE_CHARGE, $order_id, $alipay_user_id, $amount, '骑行支付:' . ($amount / 100) . "元",$pay_city);
        if (!empty($ret)) {
            $order_info = [
                'id' => $order_id,
                'city_id' => $city_id,
                'amount' => $amount,
                'user_id' => $userinfo['id'],
                'user_name' => $userinfo['name'],
                'user_phone' => $userinfo['phone'],
                'create_time' => date('Y-m-d H:i:s'),
                'order_state' => USER_CHARGERIDE_ORDER_STATE_SUBMIT,
                'gateway' => PAY_GATEWAY_ALIPAY,
                'ride_order_id' => $ride_order_id,
                'coupon_id' => $coupon_id,
                'coupon_amount' =>$coupon_amount,
                'pay_city' => $pay_city,
                'use_score' => $use_score,
                'is_profit' => $is_profit,
            ];

            self::create($order_info);
        }
        return $ret;
    }

    //微信用户支付
    function submit_wxapp($city_id, $userinfo, $amount,$ride_order_id,$coupon_id,$coupon_amount = 0,$use_score= 0)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxapp_unifield_order($city_id, ORDER_TYPE_USER_RIDE_CHARGE, $order_id, $amount, '骑行支付',$pay_city);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }


        $platform = (new PlatformModel())->get_platform_info('wxapp');


        $prepay_info = [
            'appid' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepayid'],
            'noncestr' => uniqid(),
            'timestamp' => time(),
            'prepayid' => $ret['prepayid'],
            'partnerid' => $ret['partnerid'],
        ];


        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        $prepay_info['mch_id'] = $ret['mch_id'];

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGERIDE_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'ride_order_id' => $ride_order_id,
            'coupon_id' => $coupon_id,
            'coupon_amount' =>$coupon_amount,
            'pay_city' => $pay_city,
            'use_score' => $use_score,
        ];

        self::create($order_info);
        return $prepay_info;
    }

    //支付宝用户支付
    function submit_aliapp($city_id, $userinfo, $amount,$ride_order_id,$coupon_id,$coupon_amount = 0,$use_score = 0)
    {
        $alipay_user_id = $userinfo['alipay_user_id'];

        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade_app($city_id, ORDER_TYPE_USER_RIDE_CHARGE, $order_id, $amount, '骑行支付:' . ($amount / 100) . "元",$pay_city);
        if (!empty($ret)) {
            $order_info = [
                'id' => $order_id,
                'city_id' => $city_id,
                'amount' => $amount,
                'user_id' => $userinfo['id'],
                'user_name' => $userinfo['name'],
                'user_phone' => $userinfo['phone'],
                'create_time' => date('Y-m-d H:i:s'),
                'order_state' => USER_CHARGERIDE_ORDER_STATE_SUBMIT,
                'gateway' => PAY_GATEWAY_ALIPAY,
                'ride_order_id' => $ride_order_id,
                'coupon_id' => $coupon_id,
                'coupon_amount' =>$coupon_amount,
                'pay_city' => $pay_city,
                'use_score' => $use_score,
            ];

            self::create($order_info);
        }
        return $ret;
    }

    function finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_CHARGERIDE_ORDER_STATE_SUBMIT) {
            throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        $ride_order_info = (new UserRadingOrderModel())->query_fee_info(null, $order_info['ride_order_id']);
        if (empty($ride_order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");
        }
        if ($ride_order_info['order_state'] != RIDE_ORDER_STATE_FINISH) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "骑行订单状态不匹配!");
        }

        if ($ride_order_info['is_pay'] == 1) {
            $this->throw_myexception(ERROR_QUERY_INFO, "订单已支付!");
        }

        $fee_info = $ride_order_info['fee_info'];

        $userinfo = (new UserModel())->query_info($order_info['user_id']);

        //优惠
        if (!empty($order_info['coupon_id'])){
            $coupon_info = (new CouponModel())->query_info($order_info['coupon_id']);
            $couopon_amount = (new CouponModel())->coupon_amount($coupon_info);
            if ($couopon_amount >0){
                if ($coupon_info['type'] == 1) {
                    if ($couopon_amount > 0 && $fee_info['no_coupon_fee'] < $couopon_amount) {
                        $couopon_amount = $fee_info['no_coupon_fee'];
                    }

                    $fee_info['coupon_id'] = $coupon_info['id'];
                    $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                    $fee_info['coupon_fee'] = $couopon_amount;
                } elseif ($coupon_info['type'] == 2) {
                    $calc_amount = $fee_info['no_coupon_fee'] - ceil($couopon_amount/100*$fee_info['no_coupon_fee']);
                    if ($calc_amount > 0 && $fee_info['no_coupon_fee'] < $calc_amount) {
                        $calc_amount = $fee_info['no_coupon_fee'];
                    }
                    else {
                        $calc_amount = 0;
                    }

                    $fee_info['coupon_id'] = $coupon_info['id'];
                    $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                    $fee_info['coupon_fee'] = $calc_amount;
                }
            }
        }


        $fee_info['total'] -= $fee_info['coupon_fee'];

        $usescore= $order_info['use_score'];


        if ($usescore >0){
            if (isset($fee_info['score_need']) && $fee_info['score_need'] >0 && isset($fee_info['score_fee']) && $fee_info['score_fee'] >0) {

                $score_fee = ceil($usescore *100 / $fee_info['score_fee']);
                $fee_info['total'] -= $score_fee;
                $fee_info['score_need'] = $usescore;
            }
        }
        else{
            $fee_info['score_need'] = 0;
        }

        if ($fee_info['total'] < 0){
            $fee_info['total'] = 0;
        }

        //支付
        $is_excepion = 0;   //是否异常
        $balance_amount = 0;
        if($order_info['amount'] > $fee_info['total'])
        {
            $is_excepion = 1;

        }
        else
        {
            if ($userinfo['balance'] >0)
            {
                if ($order_info['amount'] + $userinfo['balance'] != $fee_info['total']){
                    $is_excepion = 1;
                }

                $fee_info['balance_fee'] = $userinfo['balance'];

                (new UserModel())->incr_balance($order_info['user_id'], 0 - $userinfo['balance']);
            }
            else
            {
                if ($order_info['amount'] != $fee_info['total']){
                    $is_excepion = 1;
                }
            }

            if ($usescore > 0){
                (new UserModel())->incr_score($order_info['user_id'], 0 - $usescore);

                //记录一下
                (new ExchangeModel())->record($order_info['city_id'],$userinfo,SCORE_GATEWAY_RIDEPAY,-$usescore);
            }
        }

        $fee_info['pay_fee'] = $order_info['amount'];

        $data = [
//            'original_amount' => $fee_info['total'],
            'coupon_id' => $fee_info['coupon_id'],
            'coupon_metadata' => $fee_info['coupon_metadata'],
            'distance' => $fee_info['distance'],
            'is_flush' => $fee_info['is_flush'],
            'paid_amount' => $fee_info['total'],
            'fee_info' => $fee_info,
            'violation_fine' => $fee_info['npa_fee'] + $fee_info['osvc_fee'],
            'is_pay' =>1,
        ];


        $where = [
            'id' => $order_info['ride_order_id'],
        ];


        self::update($data, $where);

        if($fee_info['pay_fee']>0){
            if($order_info['gateway'] == PAY_GATEWAY_WEIXIN ){
                (new PayModel())->add_record($ride_order_info['city_id'], $ride_order_info['user_id'], ORDER_TYPE_USER_RIDE, $order_info['ride_order_id'], PAY_GATEWAY_WEIXIN, $fee_info['pay_fee']);
            }
            else{
                (new PayModel())->add_record($ride_order_info['city_id'], $ride_order_info['user_id'], ORDER_TYPE_USER_RIDE, $order_info['ride_order_id'], PAY_GATEWAY_ALIPAY, $fee_info['pay_fee']);
            }
        }

        if($fee_info['balance_fee']>0)
            (new PayModel())->add_record($ride_order_info['city_id'], $ride_order_info['user_id'], ORDER_TYPE_USER_RIDE, $order_info['ride_order_id'], PAY_GATEWAY_WALLET, $fee_info['balance_fee']);

        if ($data['coupon_id'] && $data['is_pay'] == 1) {
            (new CouponModel())->perform($data['coupon_id'],$order_info['ride_order_id']);
            if($fee_info['coupon_fee'] >0)
                (new StatModel())->user_ride_order_amount_incr($ride_order_info['city_id'], $ride_order_info['create_time'], -$fee_info['coupon_fee'],$ride_order_info['start_svca_id']);
        }

        $pay_data = [
            'order_state' => USER_CHARGERIDE_ORDER_STATE_FINISHED,
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => $payment_info,
            'is_excepion' => $is_excepion,
        ];

        $pay_where = [
            'id' => $order_id,
        ];

        //更新订单数据
        self::update($pay_data, $pay_where);

        //redis 每日用户充值排行
        (new StatModel())->user_charge_order_amount_incr($order_info['city_id'], $order_info['amount']);

        if ($ride_order_info['city_id']){
            $now = date('Y-m-d H:i:s');
            $begin_time = "2020-05-01 00:00:00";
            $end_time = "2020-05-05 23:59:59";

            if((strtotime($now) - strtotime($begin_time) >=0)&&(strtotime($now) - strtotime($end_time) <=0)){
                if($data['is_pay'] == 1){
                    $may_amount = $order_info['coupon_amount'];
                    if($may_amount > 200 ||$may_amount <=0){
                        $may_amount = common::get_may_amount();
                    }
                    (new CouponModel())->create_coupon_May_Day($may_amount,$ride_order_info['user_id'],'五一感恩前行');
                }

            }
        }

        //分账
        if ($order_info['is_profit'] == 1 &&  $order_info['amount'] > 0) {

            $trans_id = null;
            if ($order_info['gateway'] == PAY_GATEWAY_WEIXIN){
                $trans_id = $payment_info['transaction_id'];
            }
            else if ($order_info['gateway'] == PAY_GATEWAY_ALIPAY){
                $trans_id = $payment_info['trade_no'];
            }
            if (!empty($trans_id)){
                //分账
                (new PayModel())->timer_profitshare($order_info['city_id'],$order_info['amount'],$trans_id,ORDER_TYPE_USER_RIDE_CHARGE,$order_info['gateway'],$order_info['id']);
            }

        }
    }

    function query_info($order_id)
    {
        $selectlist = [
            'city_id' => 'string',
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'refund_amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            // 'payment_info' => 'array',
            'end_time' => 'string',
            'refund_order_id' => 'string',
            'refund_amount_total' => 'int',
            'ride_order_id' => 'string',
            'coupon_id' => 'string',
            'coupon_amount' => 'int',
            'use_score' => 'int',
            'is_profit' => 'int',
        ];


        $sfs = common::array_keys($selectlist);
        $beans = [
            'id'=>$order_id,
        ];
        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }

    function query_list($cd, $pos, $limit)
    {
        $selectlist = [
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            'payment_info' => 'array',
            'end_time' => 'string',
            'oper_id' => 'string',
            'oper_name' => 'string',
            'refund_amount' => 'int',
            'refund_amount_total' => 'int',
            'refund_order_id' => 'string',
            'ride_order_id' => 'string',
            'coupon_id' => 'string',
            'use_score' => 'int',
            'is_profit' => 'int',
        ];

        $sfs = common::array_keys($selectlist);
        $beans = [
        ];
        if (isset($cd['user_id'])) {
            $beans['user_id'] = $cd['user_id'];
        }

        if (isset($cd['ride_order_id'])) {
            $beans['ride_order_id'] = $cd['ride_order_id'];
        }

        if (isset($cd['oper_id'])) {
            $beans['oper_id'] = $cd['oper_id'];
        }
        if (isset($cd['order_state'])) {
            $beans['order_state'] = $cd['order_state'];
        }
        if (isset($cd['refundable'])) {
            $beans['gateway'] = [PAY_GATEWAY_WEIXIN,PAY_GATEWAY_ALIPAY,'or'];
        }

        $rows =$this->where($beans)->field($sfs)->order('create_time','desc')->limit($pos,$limit)->select();
        return $rows->toArray();
    }

    function submit_refund($order_id, $amount, $reason)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单信息失败！");
        }

        if ($order_info['order_state'] != USER_CHARGERIDE_ORDER_STATE_FINISHED) {
            $this->throw_myexception(ERROR_QUERY_INFO, "未完成支付订单！");
        }

        $ret = (new PayModel($order_info['city_id']))->submit_refund($order_info['id'], ORDER_TYPE_USER_RIDE_CHARGE_REFUND, $amount, $reason,$order_info['is_profit']);

        $order_state = USER_CHARGERIDE_ORDER_STATE_REFUND;
        $refund_total = $order_info['refund_amount_total'] + $amount;
        if ($ret->order_state == PAY_ORDER_STATE_REFUND_FINISH) {
            $order_state = $refund_total >= $order_info['amount'] ? USER_CHARGERIDE_ORDER_STATE_REFUND_FINISH : USER_CHARGERIDE_ORDER_STATE_FINISHED;
        }

        $data = [
            'order_state' => $order_state,
            'refund_order_id' => $ret->order_id,
            'refund_amount' => $amount,
            'refund_amount_total' => $refund_total,
        ];
        if ($ret->order_state == PAY_ORDER_STATE_REFUND_FINISH) {
            $data['order_state'] = $refund_total >= $amount ? USER_CHARGERIDE_ORDER_STATE_REFUND_FINISH : USER_CHARGERIDE_ORDER_STATE_FINISHED;
            $data['payment_info'] = $ret;
            $data['end_time'] = date('Y-m-d H:i:s');
        }

        $where = [
            'id' => $order_id,
        ];

        self::update($data, $where);
//        (new UserModel())->incr_balance($order_info['user_id'], 0 - $amount);

        $userinfo = (new UserModel())->query_info($order_info['user_id']);
        $log = "用户充值退款：{$userinfo['name']}, {$userinfo['phone']} 发起退款，订单id：{$order_id}, 金额:{$amount}";
        Log::debug($log);
    }

    function refund_finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->hrow_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_CHARGERIDE_ORDER_STATE_REFUND) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        $order_state = $order_info['refund_amount_total'] >= $order_info['amount'] ? USER_CHARGERIDE_ORDER_STATE_REFUND_FINISH: USER_CHARGERIDE_ORDER_STATE_FINISHED;
        $data = [
            'order_state' => $order_state,
            'end_time' => date('Y-m-d H:i:s'),
        ];
        if ($payment_info) {
            $data['payment_info'] = $payment_info;
        }

        $where = [
            'id' => $order_id,
        ];

        self::update( $data, $where);
    }

}
